package com.zhy.view;

import ohos.agp.components.*;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

/**
 * CircleMenuLayout
 *
 * @author hw
 * @since 2021/6/30
 */
public class CircleMenuLayout extends ComponentContainer implements Component.EstimateSizeListener, Component.TouchEventListener, ComponentContainer.ArrangeListener {
    private int mRadius;
    /**
     * 该容器内child item的默认尺寸
     */
    private static final float RADIO_DEFAULT_CHILD_DIMENSION = 1 / 4f;
    /**
     * 该容器的内边距,无视padding属性，如需边距请用该变量
     */
    private static final float RADIO_PADDING_LAYOUT = 1 / 12f;
    /**
     * 当每秒移动角度达到该值时，认为是快速移动
     */
    private static final int FLINGABLE_VALUE = 300;

    /**
     * 如果移动角度达到该值，则屏蔽点击
     */
    private static final int NOCLICK_VALUE = 3;
    /**
     * 菜单的中心child的默认尺寸
     */
    private float radioDefaultCenteritemDimension = 1 / 3f;

    /**
     * 当每秒移动角度达到该值时，认为是快速移动
     */
    private int mFlingableValue = FLINGABLE_VALUE;
    /**
     * 该容器的内边距,无视padding属性，如需边距请用该变量
     */
    private float mPadding;
    /**
     * 布局时的开始角度
     */
    private double mStartAngle = 0;
    /**
     * 菜单项的文本
     */
    private String[] mItemTexts;
    /**
     * 菜单项的图标
     */
    private int[] mItemImgs;

    /**
     * 菜单的个数
     */
    private int mMenuItemCount;

    /**
     * 检测按下到抬起时旋转的角度
     */
    private float mTmpAngle;
    /**
     * 检测按下到抬起时使用的时间
     */
    private long mDownTime;

    /**
     * 判断是否正在自动滚动
     */
    private boolean isFling;

    private int mMenuItemLayoutId = ResourceTable.Layout_circle_menu_item;

    public CircleMenuLayout(final Context context) {
        this(context, null);
    }

    public CircleMenuLayout(final Context context, final AttrSet attrs) {
        this(context, attrs, "");
    }

    public CircleMenuLayout(
            final Context context,
            final AttrSet attrs,
            final String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        PixelUtil.initContext(context);
        // 无视padding
        setPadding(0, 0, 0, 0);
        setEstimateSizeListener(this);
        setArrangeListener(this);
        setTouchEventListener(this);
    }

    @Override
    public boolean onEstimateSize(int widthEstimateConfig, int heightEstimateConfig) {

        int resWidth = 0;
        int resHeight = 0;
        /**
         * 根据传入的参数，分别获取测量模式和测量值
         */
        int width = Component.EstimateSpec.getSize(widthEstimateConfig);
        int widthMode = Component.EstimateSpec.getMode(widthEstimateConfig);

        int height = Component.EstimateSpec.getSize(heightEstimateConfig);
        int heightMode = Component.EstimateSpec.getMode(heightEstimateConfig);
        /**
         * 如果宽或者高的测量模式非精确值
         */
        if (widthMode != EstimateSpec.PRECISE || heightMode != EstimateSpec.PRECISE) {
            // 主要设置为背景图的高度
            resWidth = getMinWidth();
            // 如果未设置背景图片，则设置为屏幕宽高的默认值
            resWidth = resWidth == 0 ? getDefaultWidth() : resWidth;
            resHeight = getMinHeight();
            resHeight = resHeight == 0 ? getDefaultWidth() : resHeight;
            // 如果未设置背景图片，则设置为屏幕宽高的默认值
        } else {
            // 如果都设置为精确值，则直接取小值；
            resWidth = resHeight = Math.min(width, height);
        }
        setEstimatedSize(resWidth, resHeight);
        // 获得半径
        mRadius = Math.max(getEstimatedWidth(), getEstimatedHeight());
        // menu item数量
        final int count = getChildCount();
        // menu item尺寸
        int childSize = (int) (mRadius * RADIO_DEFAULT_CHILD_DIMENSION);
        // menu item测量模式
        int childMode = EstimateSpec.PRECISE;
        // 迭代测量
        for (int i = 0; i < count; i++) {
            final Component child = getComponentAt(i);
            if (child.getVisibility() == HIDE) {
                continue;
            }
            // 计算menu item的尺寸；以及和设置好的模式，去对item进行测量
            int makeMeasureSpec = -1; //
            if (child.getId() == ResourceTable.Id_id_circle_menu_item_center) {
                makeMeasureSpec = EstimateSpec.getChildSizeWithMode((int) (mRadius * radioDefaultCenteritemDimension),
                        (int) (mRadius * radioDefaultCenteritemDimension), childMode);
            } else {
                makeMeasureSpec = EstimateSpec.getChildSizeWithMode(childSize, childSize, childMode);
            }
            child.estimateSize(makeMeasureSpec, makeMeasureSpec);
        }

        mPadding = RADIO_PADDING_LAYOUT * mRadius;
        return true;
    }

    @Override
    public boolean onArrange(int l, int t, int width, int height) {

        int layoutRadius = mRadius;

        // Laying out the child views
        final int childCount = getChildCount();

        int left, top;
        // menu item 的尺寸
        int cWidth = (int) (layoutRadius * RADIO_DEFAULT_CHILD_DIMENSION);

        // 根据menu item的个数，计算角度
        float angleDelay = 360 / (float) (getChildCount() - 1);

        // 遍历去设置menuitem的位置
        for (int i = 0; i < childCount; i++) {
            final Component child = getComponentAt(i);

            if (child.getId() == ResourceTable.Id_id_circle_menu_item_center)
                continue;

            if (child.getVisibility() == HIDE) {
                continue;
            }

            mStartAngle %= 360;

            // 计算，中心点到menu item中心的距离
            double tmp = layoutRadius / 2d - cWidth / 2d - mPadding;

            // tmp cosa 即menu item中心点的横坐标
            left = layoutRadius
                    / 2
                    + (int) Math.round(tmp
                    * Math.cos(Math.toRadians(mStartAngle)) - 1 / 2f
                    * cWidth);
            // tmp sina 即menu item的纵坐标
            top = layoutRadius
                    / 2
                    + (int) Math.round(tmp
                    * Math.sin(Math.toRadians(mStartAngle)) - 1 / 2f
                    * cWidth);

            child.arrange(left, top, cWidth, cWidth);
            // 叠加尺寸
            mStartAngle += angleDelay;
        }
        Component cView = findComponentById(ResourceTable.Id_id_circle_menu_item_center);
        if (cView != null) {
            cView.setClickedListener(component -> {
                if (mOnMenuItemClickListener != null) {
                    mOnMenuItemClickListener.itemCenterClick(component);
                }
            });
            // 设置center item位置
            int cl = layoutRadius / 2 - cView.getEstimatedWidth() / 2;
            int cr = cl;
            cView.arrange(cl, cl, cr, cr);
        }

        return true;
    }


    /**
     * MenuItem的点击事件接口
     *
     * @author zhy
     */
    public interface OnMenuItemClickListener {
        void itemClick(Component view, int pos);

        void itemCenterClick(Component view);
    }

    /**
     * MenuItem的点击事件接口
     */
    private OnMenuItemClickListener mOnMenuItemClickListener;

    /**
     * 设置MenuItem的点击事件接口
     *
     * @param mOnMenuItemClickListener mOnMenuItemClickListener
     */
    public void setOnMenuItemClickListener(
            OnMenuItemClickListener mOnMenuItemClickListener) {
        this.mOnMenuItemClickListener = mOnMenuItemClickListener;

    }

    /**
     * 记录上一次的x，y坐标
     */
    private float mLastX;
    private float mLastY;

    private final EventHandler myHandler = new EventHandler(EventRunner.create());
    /**
     * 自动滚动的Runnable
     */
    private AutoFlingRunnable mFlingRunnable;

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        MmiPoint mMmiPoint = touchEvent.getPointerPosition(touchEvent.getIndex());
        float x = mMmiPoint.getX();
        float y = mMmiPoint.getY();
        switch (touchEvent.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                mLastX = x;
                mLastY = y;
                mDownTime = System.currentTimeMillis();
                mTmpAngle = 0;
                // 如果当前已经在快速滚动
                if (isFling) {
                    // 移除快速滚动的回调
                    myHandler.removeTask(mFlingRunnable);
                    isFling = false;
                    return true;
                }

                break;
            case TouchEvent.POINT_MOVE:

                /**
                 * 获得开始的角度
                 */
                double start = getAngle(mLastX, mLastY);
                /**
                 * 获得当前的角度
                 */
                double end = getAngle(x, y);

                // Log.e("TAG", "start = " + start + " , end =" + end);
                // 如果是一、四象限，则直接end-start，角度值都是正值
                if (getQuadrant(x, y) == 1 || getQuadrant(x, y) == 4) {
                    mStartAngle += end - start;
                    mTmpAngle += end - start;
                } else
                // 二、三象限，色角度值是付值
                {
                    mStartAngle += start - end;
                    mTmpAngle += start - end;
                }
                // 重新布局
                postLayout();
                mLastX = x;
                mLastY = y;

                break;
            case TouchEvent.PRIMARY_POINT_UP:

                // 计算，每秒移动的角度
                float anglePerSecond = mTmpAngle * 1000
                        / (System.currentTimeMillis() - mDownTime);
                // 如果达到该值认为是快速移动
                if (Math.abs(anglePerSecond) > mFlingableValue && !isFling) {
                    // post一个任务，去自动滚动
                    myHandler.postSyncTask(mFlingRunnable = new AutoFlingRunnable(anglePerSecond));
                    return true;
                }

                // 如果当前旋转角度超过NOCLICK_VALUE屏蔽点击
                if (Math.abs(mTmpAngle) > NOCLICK_VALUE) {
                    return true;
                }

                break;
        }
        return true;
    }

    /**
     * 根据触摸的位置，计算角度
     *
     * @param xTouch xTouch
     * @param yTouch yTouch
     * @return Angle
     */
    private float getAngle(float xTouch, float yTouch) {
        double x = xTouch - (mRadius / 2d);
        double y = yTouch - (mRadius / 2d);
        return (float) (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
    }

    /**
     * 根据当前位置计算象限
     *
     * @param x X轴
     * @param y Y轴
     * @return Quadrant
     */
    private int getQuadrant(float x, float y) {
        int tmpX = (int) (x - mRadius / (double) 2);
        int tmpY = (int) (y - mRadius / (double) 2);
        if (tmpX >= 0) {
            return tmpY >= 0 ? 4 : 1;
        } else {
            return tmpY >= 0 ? 3 : 2;
        }

    }

    /**
     * 设置菜单条目的图标和文本
     *
     * @param resIds resIds
     * @param texts texts
     *
     * @throws IllegalArgumentException 菜单项文本和图片至少设置其一
     */
    public void setMenuItemIconsAndTexts(int[] resIds, String[] texts) {
        if (resIds != null) {
            mItemImgs = resIds.clone();
        }
        if (texts != null) {
            mItemTexts = texts.clone();
        }

        // 参数检查
        if (resIds == null && texts == null) {
            throw new IllegalArgumentException("菜单项文本和图片至少设置其一");
        }

        // 初始化mMenuCount
        mMenuItemCount = resIds == null ? texts.length : resIds.length;

        if (resIds != null && texts != null) {
            mMenuItemCount = Math.min(resIds.length, texts.length);
        }

        addMenuItems();

    }

    /**
     * 设置MenuItem的布局文件，必须在setMenuItemIconsAndTexts之前调用
     *
     * @param mMenuItemLayoutId mMenuItemLayoutId
     */
    public void setMenuItemLayoutId(int mMenuItemLayoutId) {
        this.mMenuItemLayoutId = mMenuItemLayoutId;
    }

    /**
     * 添加菜单项
     */
    private void addMenuItems() {
        if (getChildCount() > 1) {
            return;
        }
        LayoutScatter mLayoutScatter = LayoutScatter.getInstance(getContext());
        /**
         * 根据用户设置的参数，初始化view
         */
        for (int i = 0; i < mMenuItemCount; i++) {
            final int j = i;
            Component view = mLayoutScatter.parse(mMenuItemLayoutId, this, false);
            Image iv = (Image) view.findComponentById(ResourceTable.Id_id_circle_menu_item_image);
            DirectionalLayout.LayoutConfig mLayoutConfig = (DirectionalLayout.LayoutConfig) iv.getLayoutConfig();
            mLayoutConfig.width = (int) PixelUtil.vp2px(53);
            mLayoutConfig.height = (int) PixelUtil.vp2px(53);
            iv.setLayoutConfig(mLayoutConfig);
            Text tv = (Text) view.findComponentById(ResourceTable.Id_id_circle_menu_item_text);
            iv.setVisibility(VISIBLE);
            iv.setImageAndDecodeBounds(mItemImgs[i]);
            iv.setClickedListener(new ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (mOnMenuItemClickListener != null) {
                        mOnMenuItemClickListener.itemClick(component, j);
                    }
                }
            });
            tv.setVisibility(VISIBLE);
            tv.setText(mItemTexts[i]);
            // 添加view到容器中
            addComponent(view);
        }
    }

    /**
     * 如果每秒旋转角度到达该值，则认为是自动滚动
     *
     * @param mFlingableValue mFlingableValue
     */
    public void setFlingableValue(int mFlingableValue) {
        this.mFlingableValue = mFlingableValue;
    }

    /**
     * 设置内边距的比例
     *
     * @param mPadding mPadding
     */
    public void setPadding(float mPadding) {
        this.mPadding = mPadding;
    }

    /**
     * 获得默认该layout的尺寸
     *
     * @return Width
     */
    private int getDefaultWidth() {
        return Math.min(PixelUtil.screenWidth(), PixelUtil.screenHeight());
    }

    /**
     * 自动滚动的任务
     *
     * @author zhy
     */
    private class AutoFlingRunnable implements Runnable {
        //每秒移动的角度
        private float angelPerSecond;

        public AutoFlingRunnable(float velocity) {
            this.angelPerSecond = velocity;
        }

        public void run() {
            // 如果小于20,则停止
            if ((int) Math.abs(angelPerSecond) < 20) {
                isFling = false;
                return;
            }
            isFling = true;
            // 不断改变mStartAngle，让其滚动，/30为了避免滚动太快
            mStartAngle += (angelPerSecond / 30);
            // 逐渐减小这个值
            angelPerSecond /= 1.0666F;
            myHandler.postTask(this, 30);
            // 重新布局
            CircleMenuLayout.this.mContext.getUITaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    postLayout();
                }
            });
        }
    }

}
       